package org.example.workbench.controller;

import org.example.commons.constant.Constant;
import org.example.commons.domain.ErrorInfo;
import org.example.commons.utils.DateFormatUtils;
import org.example.commons.utils.UUIDUtils;
import org.example.settings.domain.DictionaryValue;
import org.example.settings.domain.User;
import org.example.settings.service.DictionaryValueService;
import org.example.settings.service.UserService;
import org.example.workbench.domain.*;
import org.example.workbench.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Controller
@RequestMapping("/contacts")
public class contactsController {
    @Autowired
    private ContactsService contactsService;
    @Autowired
    private DictionaryValueService dictionaryValueService;
    @Autowired
    private UserService userService;
    @Autowired
    private CustomerService customerService;

    @Autowired
    private ContactsRemarkService contactsRemarkService;
    @Autowired
    private TranService tranService;
    @Autowired
    private ActivityService activityService;
    @RequestMapping("/toSaveTran")
    public String toSaveJsp(HttpServletRequest request,String contactsId,String currentContactsName){
        List<User> userList = userService.findAll();
        List<DictionaryValue> stageList = dictionaryValueService.selectDicValueByType(Constant.STAGE);
        List<DictionaryValue> tranList = dictionaryValueService.selectDicValueByType(Constant.TRANSACTION_TYPE);
        List<DictionaryValue> sourceList = dictionaryValueService.selectDicValueByType(Constant.SOURCE);
        request.setAttribute("userList",userList);
        request.setAttribute("stageList",stageList);
        request.setAttribute("tranList",tranList);
        request.setAttribute("sourceList",sourceList);
        request.setAttribute("contactsId",contactsId);
        request.setAttribute("currentContactsName",currentContactsName);
        return "workbench/contacts/saveTran";
    }
    @RequestMapping("/getContactsDetail")
    public String getContactsDetail(String contactsId,HttpServletRequest request){
        Contacts contacts = contactsService.getOneContactsDetailById(contactsId);
        List<ContactsRemark> contactsRemarkList = contactsRemarkService.getContactsRemarkByContactsId(contactsId);
        List<Tran> tranList = tranService.getTranByContactsId(contactsId);
        List<activity> activityList = activityService.getActivityByContactsId(contactsId);
        ResourceBundle bundle = ResourceBundle.getBundle("possibility", Locale.getDefault(), new ResourceBundle.Control() {
            @Override
            public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
                // 使用 UTF-8 编码加载 properties 文件
                String bundleName = toBundleName(baseName, locale);
                String resourceName = toResourceName(bundleName, "properties");
                try (InputStream stream = loader.getResourceAsStream(resourceName)) {
                    return new PropertyResourceBundle(new InputStreamReader(stream, StandardCharsets.UTF_8));
                }
            }
        });
        for (Tran tran : tranList) {
            String possibility = bundle.getString(tran.getStage());
            tran.setPossibility(possibility);
        }
        request.setAttribute("contacts",contacts);
        request.setAttribute("contactsRemarkList",contactsRemarkList);
        request.setAttribute("tranList",tranList);
        request.setAttribute("activityList",activityList);
        return "workbench/contacts/detail";
    }
    @RequestMapping("/updateOneContactsByContact")
    public @ResponseBody Object updateOneContactsByContact(Contacts contacts,HttpSession session){
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        contacts.setEditBy(user.getId());
        contacts.setEditTime(DateFormatUtils.formatDateTime(new Date()));
        String customerName = contacts.getCustomerId();
        Customer customer = customerService.getCustomerDetailByName(customerName);
        contacts.setCustomerId(customer.getId());
        ErrorInfo errorInfo = new ErrorInfo();
        try{
            int i = contactsService.updateOneContactsByContact(contacts);
            if (i>0){
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
            }else {
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
                errorInfo.setErrorMessage("系统繁忙，请稍后.......");
            }
        }catch (Exception e){
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙，请稍后.......");
        }
        return errorInfo;
    }
    @RequestMapping("/deleteOneContactsById")
    public @ResponseBody Object deleteOneContactsById(String id){
        ErrorInfo errorInfo = new ErrorInfo();
        try{
            int i = contactsService.deleteOneContactsById(id);
            if (i>0){
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
            }else {
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
                errorInfo.setErrorMessage("系统繁忙，请稍后.......");
            }
        }catch (Exception e){
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙，请稍后.......");
        }
        return errorInfo;
    }
    @RequestMapping("/getOneContactsById")
    public @ResponseBody Object getOneContactsById(String id){
        ErrorInfo errorInfo = new ErrorInfo();
        Contacts contacts =null;
        try{
            contacts = contactsService.getOneContactsById(id);
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
        }catch (Exception e){
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙，请稍后.......");
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("errorInfo",errorInfo);
        hashMap.put("contacts",contacts);
        return hashMap;
    }
    @RequestMapping("/insertOneContactsByContacts")
    public @ResponseBody Object insertOneContactsByContacts(Contacts contacts, HttpSession session){
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        ErrorInfo errorInfo = new ErrorInfo();
        try{
            contacts.setId(UUIDUtils.getUUID());
            contacts.setCreateTime(DateFormatUtils.formatDateTime(new Date()));
            contacts.setCreateBy(user.getId());
            String customerName = contacts.getCustomerId();
            Customer customer = customerService.getCustomerDetailByName(customerName);
            contacts.setCustomerId(customer.getId());
            int i = contactsService.insertOneContactsByContacts(contacts);
            if (i>0){
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
            }else {
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
                errorInfo.setErrorMessage("系统繁忙，请稍后.......");
            }
        }catch (Exception e){
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙，请稍后.......");
        }
        return errorInfo;
    }
    @RequestMapping("/getContactsPages")
    public @ResponseBody Object getContactsPages(@RequestParam Map<String,Object> map){
        int currentPage = Integer.parseInt((String) map.get("currentPage"));
        int pageSize = Integer.parseInt((String) map.get("pageSize"));
        int pageNo=(currentPage-1)*pageSize;
        map.put("pageNo",pageNo);
        map.put("pageSize",pageSize);
        List<Contacts> contactsList = contactsService.getContactsByMap(map);
        int totalCount = contactsService.getTotalContactsCount(map);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("contactsList",contactsList);
        hashMap.put("totalCount",totalCount);
        return hashMap;
    }
    @RequestMapping("/index")
    public String index(HttpServletRequest request){
        //获取所有字典信息
        List<DictionaryValue> sourceList = dictionaryValueService.selectDicValueByType(Constant.SOURCE);
        List<DictionaryValue> appellationList = dictionaryValueService.selectDicValueByType(Constant.APPELLATION);
        List<User> userList = userService.findAll();
        //发送信息
//        request.setAttribute("contactsList",contactsList);
        request.setAttribute("sourceList",sourceList);
        request.setAttribute("appellationList",appellationList);
        request.setAttribute("userList",userList);
        return "workbench/contacts/index";
    }
    @RequestMapping("/getContactsByName")
    public @ResponseBody Object getContactsByName(String contactsName){
        return contactsService.getContactsByName(contactsName);
    }
}
